<template>
  <div id="app">
    <FileSelector @filechange="onFileChange" />
    <div>
      <ConfigTable
        :channels="simpleChannels" :polyData="polyData" :baseIndex="baseIndex"
        @draw="onDraw" />
    </div>
    <div id="chart" class="chart-box"></div>
  </div>
</template>

<script>
import echarts from 'echarts';
import ecStat from 'echarts-stat';
import FileSelector from './components/FileSelector.vue';
import ConfigTable from './components/ConfigTable.vue';

let chartLoading = null;
let chart;
const chartOption = {
  legend: {
    x: 'left',
    data: [],
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
    },
  },
  toolbox: {
    feature: {
      saveAsImage: {},
      restore: {},
      dataZoom: {},
    },
  },
  xAxis: {
    type: 'value',
    scale: true,
    splitLine: {
      lineStyle: {
        type: 'dashed',
      },
    },
  },
  yAxis: {
    type: 'value',
    scale: true,
    splitLine: {
      lineStyle: {
        type: 'dashed',
      },
    },
  },
  series: [],
};

export default {
  name: 'app',

  components: {
    FileSelector,
    ConfigTable,
  },

  data() {
    return {
      simpleChannels: [],
      polyData: [],
      baseIndex: 0,
    };
  },

  mounted() {
    chart = echarts.init(document.getElementById('chart'));
    chart.on('finished', () => {
      setTimeout(() => {
        if (chartLoading !== null) {
          chartLoading.close();
          chartLoading = null;
        }
      }, 100);
    });

    window.onresize = () => {
      chart.resize();
    };
  },

  methods: {
    onFileChange(result) {
      chart.clear();
      if (result.valid === true) {
        this.simpleChannels = result.channels.flatMap((ch) => {
          const obj = {
            title: `${ch.title}(${ch.unit})`,
            data: ch.data,
          };
          return obj;
        });
        this.baseIndex = result.baseIndex;
      } else {
        this.simpleChannels = [];
      }
      this.polyData = [];
    },
    onDraw(curves) {
      if (curves.length === 0) {
        return;
      }

      chartLoading = this.$loading({
        lock: true,
        text: '画图中',
        spinner: 'el-icon-loading',
        background: 'rgba(68, 68, 68, 0.7)',
      });

      chart.clear();

      const polyArray = [];

      chartOption.series = curves.flatMap((c) => {
        const op = {
          name: c.name,
          type: 'scatter',
          itemStyle: {
            color: c.color,
          },
          data: c.data,
        };

        if (c.poly !== 0) {
          const myRegression = ecStat.regression('polynomial', c.data, c.poly);
          polyArray.push({
            name: c.name,
            expression: myRegression.expression,
            parameter: myRegression.parameter,
          });
          myRegression.points.sort((a, b) => a[0] - b[0]);

          const polyOp = {
            name: `${c.name}_拟合`,
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: myRegression.points,
            markPoint: {
              itemStyle: {
                normal: {
                  color: 'transparent',
                },
              },
              label: {
                show: true,
                position: 'left',
                formatter: myRegression.expression,
                textStyle: {
                  color: '#333',
                  fontSize: 14,
                },
              },
              data: [{
                coord: myRegression.points[myRegression.points.length - 1],
              }],
            },
          };

          return [op, polyOp];
        }

        return op;
      });

      if (polyArray.length > 0) {
        this.polyData = polyArray.map(p => `${p.name}, ${p.parameter.join(',')}`);
      }

      chartOption.legend.data = chartOption.series.map(s => s.name);

      chart.setOption(chartOption);
    },
  },
};
</script>

<style>
.chart-box {
  height: 600px;
}
</style>
